import os
from PIL import Image
import xml.etree.ElementTree as ET

SCML_FILE_NAME = "esctemplate.scml"  ## scml 文件名
SIDE_EXPANSION_PIX = 200               ## 单边至少拓展多少像素

def parse_xml(file_path):
    tree = ET.parse(file_path)
    root = tree.getroot()
    
    pivot_data = {}
    for file_elem in root.findall('.//file'):
        full_name = file_elem.attrib.get('name', '')
        file_name = os.path.basename(full_name)
        width = int(file_elem.attrib.get('width', 0))
        height = int(file_elem.attrib.get('height', 0))
        pivot_x = float(file_elem.attrib.get('pivot_x', 0))
        pivot_y = float(file_elem.attrib.get('pivot_y', 0))
        
        if file_name and width > 0 and height > 0:
            pivot_data[file_name] = {
                'pivot_x': pivot_x,
                'pivot_y': pivot_y,
                'full_path': os.path.join(os.path.dirname(file_path), full_name),
                'original_width': width,
                'original_height': height
            }
    
    return root, pivot_data

def expand_image(image_path, original_width, original_height, pivot_x, pivot_y, expansion=SIDE_EXPANSION_PIX):
    with Image.open(image_path) as img:
        width, height = img.size
        
        # Ensure the original dimensions match the XML attributes
        if width != original_width or height != original_height:
            raise ValueError(f"Image dimensions do not match XML attributes for {image_path}")
        
        # Calculate new dimensions based on expansion value
        new_width = width + 2 * expansion
        new_height = height + 2 * expansion
        
        # Create a new transparent image
        new_img = Image.new('RGBA', (new_width, new_height), (0, 0, 0, 0))
        
        # Calculate the position of the original image on the new canvas
        orig_x = int(new_width * pivot_x - original_width * pivot_x)
        # Adjusting the y position to ensure the anchor point remains in the same relative position vertically
        orig_y = int(new_height * (1 - pivot_y) - original_height * (1 - pivot_y))
        
        # Paste the original image onto the new canvas
        new_img.paste(img, (orig_x, orig_y))
        
        # Save the new image back to the same path, replacing the old one
        new_img.save(image_path)

        return new_width, new_height
def update_xml(root, pivot_data, expansion=SIDE_EXPANSION_PIX):
    for file_elem in root.findall('.//file'):
        file_name = os.path.basename(file_elem.attrib.get('name', ''))
        if file_name in pivot_data:
            full_path = pivot_data[file_name]['full_path']
            pivot_x = pivot_data[file_name]['pivot_x']
            pivot_y = pivot_data[file_name]['pivot_y']
            original_width = pivot_data[file_name]['original_width']
            original_height = pivot_data[file_name]['original_height']
            
            if os.path.exists(full_path):
                new_width, new_height = expand_image(
                    full_path, 
                    original_width, 
                    original_height, 
                    pivot_x, 
                    pivot_y, 
                    expansion
                )
                # Update XML attributes
                file_elem.set('width', str(new_width))
                file_elem.set('height', str(new_height))
            else:
                print(f"Warning: File {full_path} does not exist.")
    
    # Save the updated XML file
    tree = ET.ElementTree(root)
    tree.write(xml_file_path, encoding='utf-8', xml_declaration=True)

# 主程序入口
if __name__ == "__main__":
    script_dir = os.path.dirname(os.path.abspath(__file__))  # 获取脚本所在目录
    xml_file_path = os.path.join(script_dir, SCML_FILE_NAME)
    
    # 解析XML文件获取pivot数据和根元素
    root, pivot_data = parse_xml(xml_file_path)
    
    # 处理PNG文件并替换原文件，同时更新XML中的宽度和高度信息
    update_xml(root, pivot_data)